package com.liuhouse.handler.security;

import com.alibaba.fastjson.JSON;
import com.liuhouse.enums.AppHttpCodeEnum;
import com.liuhouse.utils.ResponseResult;
import com.liuhouse.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
//自定义认证失败处理器 AuthenticationEntryPoint 这是官方提供的 AuthenticationEntryPoint 自定义认证失败处理器
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    //在认证的时候会自动调用commence此方法
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        //输出异常信息
        authException.printStackTrace();
        ResponseResult result = null;
        if(authException instanceof BadCredentialsException){
            result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode() ,authException.getMessage());
        } else if (authException instanceof InsufficientAuthenticationException) {
            result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }else{
            result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode() , "认证或者授权失败");
        }
        //使用spring提供的JSON工具类,把上一行的result转换成JSON，然后响应给前端,WebUtils是我们写的类
        //BadCredentialsException 登录异常  这是 secetry内置的异常，会自动捕获到 框架内置的 现在会用即可
        //权限异常 springSectry我没有学过
        //InsufficientAuthenticationException
        WebUtils.renderString(response , JSON.toJSONString(result));
    }
}
